package io.polly.secure;

import java.util.List;
import java.util.concurrent.RecursiveTask;


/**
 * @author ldz
 * @version V1.0
 * @title: ForkJoinTask
 * @description: TODO(用一句话描述该文件做什么)
 * @date: 2022/4/1 15:42
 */

public class ForkJoinTask extends RecursiveTask<Integer>  {

        // 分片阈值
        public static final int threshold = 100;
        private int start;
        private int end;
        private List<Integer> list;

        public ForkJoinTask(int start, int end, List<Integer> list) {
            this.start = start;
            this.end = end;
            this.list = list;
        }


        @Override
        protected Integer compute() {
            System.out.println(Thread.currentThread().getName());
            // 小于阈值直接执行
            Integer sum=0;
            if (end - start <= threshold) {
                for (int i = start; i < end; i++) {
                    sum += list.get(i);
                }
                return sum;
            }    else {
                // 递归拆解任务
                int middle = (start + end) / 2;
                ForkJoinTask leftTask = new ForkJoinTask(start, middle,list);
                ForkJoinTask rightTask = new ForkJoinTask(middle, end,list);
                invokeAll(leftTask, rightTask);
                // 等待计算完成并返回计算结果。
                return  leftTask.join()+ rightTask.join();
            }


        }






}
